/*
 DNN Content Builder - sourceforge.net/projects/dnncb
 Copyright (c) 2004-2008
 by Emerson Lopes (emersonlopes@gmail.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Tabs;

namespace DNNContentBuilder.UserControls
{
    /// <summary>
	///		Summary description.
	/// </summary>
	public class TemplateDetailsControl : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		public const string resource = "~/DesktopModules/DNNContentBuilder/App_LocalResources/TemplateDetailsControl";

		protected Literal ltErrorMessage;
		protected LinkButton btUpdate;
		protected CheckBoxList cblModules;
		protected LinkButton btCancel;

		protected TemplateDefinitionController tdController = new TemplateDefinitionController();
		protected TemplateDefinitionInfo tdInfo = new TemplateDefinitionInfo();
		protected ContentViewerSettingsController cvsController = new ContentViewerSettingsController();

		protected ContentViewerSettingsInfo cvsInfo = new ContentViewerSettingsInfo();

		protected Int32 mTemplateId;
		
		protected string image = "";

		[Bindable(false)]
		[Browsable(true)]
		[Category("Behavior")]
		public event TemplateDetailsEventHandler TemplateDetailsClicked;
		
		private void Page_Load(object sender, EventArgs e)
		{
			image = "<img src='" + Page.ResolveUrl("~/DesktopModules/DNNContentBuilder/images/rightArrow.gif") + "'>";

			if (cblModules.Items.Count == 0) {
				BuildTemplateList();
			}

			this.btCancel.Text			= Commons.GetLocalizedString("button_Cancel", resource);
			this.btUpdate.Text			= Commons.GetLocalizedString("button_Update", resource);
			
			// Put user code to initialize the page here

		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btUpdate.Click += new System.EventHandler(this.btUpdate_Click);
			this.btCancel.Click += new System.EventHandler(this.btCancel_Click);
			this.Load += new System.EventHandler(this.Page_Load);
		}

		#endregion

		private void ShowError(string message, string error) {
			ltErrorMessage.Visible = true;
			ltErrorMessage.Text = @"
			<script language='javascript'>
			<!-- 
			    alert('{0}') 
			-->
			</script>
			";
			ltErrorMessage.Text = String.Format(ltErrorMessage.Text, message);
			ltErrorMessage.Text = String.Format(ltErrorMessage.Text, error).Replace("\r","").Replace("\n","");
			ltErrorMessage.Text = ltErrorMessage.Text.Replace("<!--","\n<!--\n").Replace("-->","\n-->\n");
		}
		
		public void ClearItems() {
				BuildTemplateList();
		}

		private void btUpdate_Click(object sender, EventArgs e)
		{
			using (ConnectionProvider cp = new ConnectionProvider())
			using (ContentViewerSettingsController cvsController = new ContentViewerSettingsController(cp))
			{
				cp.BeginTransaction();
				
				foreach (ListItem listItem in cblModules.Items) {
					ArrayList cvs = cvsController.GetByModule(Int32.Parse(listItem.Value));
					
					ContentViewerSettingsInfo info = new ContentViewerSettingsInfo();
					
					bool newAssociation = true;
					
					if (cvs != null && cvs.Count > 0) {
						info = (ContentViewerSettingsInfo)cvs[0];
						newAssociation = false;
					}
				
					System.Web.UI.UserControl control = (System.Web.UI.UserControl)NamingContainer.NamingContainer.FindControl("TemplateWorkbenchControl1");

					if (listItem.Selected) {
						info.TemplateDefinitionId = ((TemplateWorkbenchControl)control).TemplateId;
						
						if (newAssociation) {
							info.ModuleID = Int32.Parse(listItem.Value);
							cvsController.Add(info);
						} else {
							cvsController.Update(info);
						}
					} else {
						if (info.ModuleID == ((TemplateWorkbenchControl)control).TemplateId) {
							cvsController.Delete(info.ContentViewerSettingsId);
						}
					}
				}
				
				cp.Commit();
			}

  			cblModules.Items.Clear();
			
			TemplateDetailsClicked(sender, new TemplateDetailsEventArgs("UPDATE"));
		}

		private void btCancel_Click(object sender, EventArgs e)
		{
  			cblModules.Items.Clear();

			TemplateDetailsClicked(sender, new TemplateDetailsEventArgs("CANCEL"));
		}
		
		private void BuildTemplateList()
		{
			ArrayList list = new ArrayList();
			
			ArrayList tabs = new TabController().GetTabs(ContextUtil.GetPortalId(this));
			
			foreach (TabInfo tabInfo in tabs)
			{
				// Build the first level items and proceed from there
				if (tabInfo.Level == 0)
				{
					if (!tabInfo.IsAdminTab && !tabInfo.IsDeleted && !tabInfo.IsSuperTab) {
						list = CreateNode(tabInfo.TabID, image + tabInfo.TabName + image, list);
						
						ArrayList modules = new DotNetNuke.Entities.Modules.ModuleController().GetPortalTabModules(ContextUtil.GetPortalId(this), tabInfo.TabID);
						
						if (modules != null) {

							foreach (DotNetNuke.Entities.Modules.ModuleInfo module in modules) {
								if (module.ModuleName.ToUpper().Trim() == "CONTENT VIEWER") {
									list.Add(new Pair(image + tabInfo.TabName + image + module.ModuleTitle + "(" + module.ModuleID + ")", module.ModuleID.ToString()));
								}
							}
						}
					}
				}
			}
			
			cblModules.Items.Clear();
			
			cblModules.Attributes.Add("style", "font-family:verdana; font-size: 10px;");
			
			SortedList orderedList = new SortedList();

			// defining a hash to prevent shadow modules to be added to the list
			Hashtable hash = new Hashtable();
			
			foreach (Pair pair in list) {
				if (!hash.ContainsValue(pair.Value)) {
					orderedList.Add(pair.Name, pair);
					hash.Add(pair.Name, pair.Value);
				}
			}
			
			foreach (Pair pair in orderedList.Values) {
				ArrayList cvs = cvsController.GetByModule(Int32.Parse(pair.Value));

				bool isSelected = false;

				if (cvs != null && cvs.Count > 0) {
					ContentViewerSettingsInfo cvsInfo = (ContentViewerSettingsInfo)cvs[0];
					if (cvsInfo != null) {
						if (cvsInfo.TemplateDefinitionId != Null.NullInteger) {
							TemplateDefinitionController tdController = new TemplateDefinitionController();
							TemplateDefinitionInfo tdInfo = tdController.GetItem(cvsInfo.TemplateDefinitionId);
							if (tdInfo != null) {
								pair.Name = pair.Name + "<b>(" + tdInfo.TemplateName.Replace(HttpContext.Current.Server.MapPath(@"~\DesktopModules\DNNContentBuilder\Templates"), "").Substring(1) + ")</b>";

								System.Web.UI.UserControl control = (System.Web.UI.UserControl)NamingContainer.NamingContainer.FindControl("TemplateWorkbenchControl1");

								if (tdInfo.TemplateDefinitionId == ((TemplateWorkbenchControl)control).TemplateId) {
								    isSelected = true;
								}
							}
						}
					}
				}
				
				ListItem listItem = new ListItem(pair.Name, pair.Value);
				
				listItem.Selected = isSelected;
				
				cblModules.Items.Add(listItem);
			}
		
		}
		
		private ArrayList CreateNode(int parentId, string path, ArrayList list) {
			ArrayList tabs = new TabController().GetTabsByParentId(parentId);

			foreach (TabInfo tabInfo in tabs)
			{
				if (!tabInfo.IsAdminTab && !tabInfo.IsDeleted && !tabInfo.IsSuperTab) {
					// Create treeview item
					
					path = path + tabInfo.TabName + image;
					
					list = CreateNode(tabInfo.TabID, path, list);

					ArrayList modules = new DotNetNuke.Entities.Modules.ModuleController().GetPortalTabModules(ContextUtil.GetPortalId(this), tabInfo.TabID);
					
					if (modules != null) {
						foreach (DotNetNuke.Entities.Modules.ModuleInfo module in modules) {
							if (module.ModuleName.ToUpper().Trim() == "CONTENT VIEWER") {
								list.Add(new Pair(path + module.ModuleTitle + "(" + module.ModuleID + ")", module.ModuleID.ToString()));
							}
						}
					}
				}
			}

			return list;
		}
	}
}
